package com.powernode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.constant.AuthConstant;
import com.powernode.domain.SysLoginUser;
import com.powernode.mapper.SysLoginUserMapper;
import com.powernode.service.LoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author syo 2319615164@qq.com
 * @description
 * @date 2024/10/3
 * @Copyright syo
 */
@Service(AuthConstant.SYS_USER)
@RequiredArgsConstructor
public class SysUserLoginServiceImpl implements LoginService {

    private final SysLoginUserMapper sysLoginUserMapper;

    /**
     * 根据输入的username查询用户
     * @param username  用户名
     * @return          返回给框架的UserDetails对象
     */
    @Override
    public UserDetails realLogin(String username) {
        // 1. 根据用户名查询用户
        SysLoginUser sysLoginUser = sysLoginUserMapper
                .selectOne(new LambdaQueryWrapper<SysLoginUser>()
                        .eq(SysLoginUser::getUsername, username));

        if (sysLoginUser != null) {
            // 2. 根据用户标识查询用户的权限集合
            List<String> auths = sysLoginUserMapper.selectAuthsByUserId(sysLoginUser.getUserId());

            // 3. 设置用户权限
            sysLoginUser.setAuths(auths);

            // 4. 设置登录类型
            sysLoginUser.setLoginType(AuthConstant.SYS_USER);

            return sysLoginUser;
        }

        return null;
    }
}
